from rest_framework import status, viewsets, filters
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from rest_framework.response import Response
from .models import Note, Like
from .serializers import NoteSerializer, NoteCreateSerializer, NoteUpdateSerializer

class NoteViewSet(viewsets.ModelViewSet):
    """笔记视图集，处理笔记的CRUD操作"""
    queryset = Note.objects.filter(is_public=True).order_by('-created_at')
    serializer_class = NoteSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['title', 'content', 'author__username']
    ordering_fields = ['created_at', 'updated_at', 'likes_count']
    ordering = ['-created_at']
    
    def get_serializer_class(self):
        """根据不同的操作选择不同的序列化器"""
        if self.action == 'create':
            return NoteCreateSerializer
        elif self.action in ['update', 'partial_update']:
            return NoteUpdateSerializer
        return NoteSerializer
    
    def get_queryset(self):
        """获取查询集，根据用户身份过滤"""
        queryset = super().get_queryset()
        
        # 如果是登录用户，可以查看自己的所有笔记（包括非公开的）
        if self.request.user.is_authenticated:
            user_notes = Note.objects.filter(author=self.request.user)
            queryset = (queryset | user_notes).distinct()
        
        # 过滤条件
        author_id = self.request.query_params.get('author_id')
        if author_id:
            queryset = queryset.filter(author_id=author_id)
        
        return queryset
    
    def perform_create(self, serializer):
        """创建笔记时设置作者"""
        serializer.save(author=self.request.user)
    
    def perform_update(self, serializer):
        """更新笔记前检查权限"""
        note = self.get_object()
        if note.author != self.request.user:
            raise PermissionError('您没有权限修改这篇笔记')
        serializer.save()
    
    def perform_destroy(self, instance):
        """删除笔记前检查权限"""
        if instance.author != self.request.user:
            raise PermissionError('您没有权限删除这篇笔记')
        instance.delete()
    
    @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated])
    def like(self, request, pk=None):
        """笔记点赞功能"""
        note = self.get_object()
        user = request.user
        
        # 检查是否已经点赞
        like, created = Like.objects.get_or_create(user=user, note=note)
        
        if created:
            return Response({
                'status': 'success',
                'message': '点赞成功',
                'likes_count': note.likes_count
            }, status=status.HTTP_200_OK)
        else:
            # 取消点赞
            like.delete()
            return Response({
                'status': 'success',
                'message': '已取消点赞',
                'likes_count': note.likes_count
            }, status=status.HTTP_200_OK)
    
    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def my_notes(self, request):
        """获取当前用户的所有笔记"""
        notes = Note.objects.filter(author=request.user).order_by('-created_at')
        page = self.paginate_queryset(notes)
        if page is not None:
            serializer = self.get_serializer(page, many=True, context={'request': request})
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(notes, many=True, context={'request': request})
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'], permission_classes=[IsAuthenticated])
    def liked_notes(self, request):
        """获取当前用户点赞的所有笔记"""
        liked_note_ids = Like.objects.filter(user=request.user).values_list('note_id', flat=True)
        notes = Note.objects.filter(id__in=liked_note_ids).order_by('-created_at')
        page = self.paginate_queryset(notes)
        if page is not None:
            serializer = self.get_serializer(page, many=True, context={'request': request})
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(notes, many=True, context={'request': request})
        return Response(serializer.data)